package cn.shyouchi.wuguanjia.android.ui.home.security.thread.contact;


import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.iasii.app.citylist.utils.DensityUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.home.HomeApi;
import cn.shyouchi.wuguanjia.android.base.BaseFragment;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.widget.LetterListView;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.R.id.topBar;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContactFragment extends BaseFragment implements LetterListView.OnTouchingLetterChangedListener {


    @BindView(topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_contact)
    RecyclerView mRvContact;
    @BindView(R.id.lt_view)
    LetterListView mLtView;
    ContactAdapter mContactAdapter;
    HomeApi mHomeApi;


    //    List<Contacter> mContactEntities = new ArrayList<>();
    List<ContactSection> mContactSectionEntities = new ArrayList<>();

    boolean isFirst = true;

    TextView letterOverlay;

    OverlayThread overlayThread;

    private Map<String, Integer> letterIndex = new HashMap<>();


    public ContactFragment() {

    }


    @Override
    public void initInjector() {

        if (mHomeApi == null) {
            mHomeApi = new HomeApi(getContext());
        }


    }

    @Override
    public int initContentView() {
        return R.layout.fragment_contact;
    }

    @Override
    public void getBundle(Bundle bundle) {

    }

    @Override
    public void initUI(View view) {
        ButterKnife.bind(this, view);
        mTopBar.setTitle("通讯录");

        showContent(false);

        mLtView.setOnTouchingLetterChangedListener(this);


        mContactAdapter = new ContactAdapter(mContactSectionEntities);
        mRvContact.setAdapter(mContactAdapter);
        mRvContact.setLayoutManager(new LinearLayoutManager(getContext()));

        initOverlay();


    }

    @Override
    public void onTouchUp() {

        letterOverlay.postDelayed(overlayThread, 1000);
    }

    @Override
    public void initData() {
        if (isFirst) {
            fetchContactList();
            isFirst = false;
        }
    }


    /**
     * a-z排序
     */
    Comparator comparator = new Comparator<Contacter>() {
        @Override
        public int compare(Contacter lhs, Contacter rhs) {
            String a = lhs.getPinyin().substring(0, 1);
            String b = rhs.getPinyin().substring(0, 1);
            int flag = a.compareTo(b);
            if (flag == 0) {
                return a.compareTo(b);
            } else {
                return flag;
            }
        }
    };


    private void fetchContactList() {
        mHomeApi.fetchContact()
                .subscribeOn(Schedulers.io())
                .map(new Func1<ContactEntity, List<Contacter>>() {
                    @Override
                    public List<Contacter> call(ContactEntity entity) {
                        return entity.getResultMessage();
                    }
                }).map(new Func1<List<Contacter>, List<Contacter>>() {
            @Override
            public List<Contacter> call(List<Contacter> contacters) {
                Collections.sort(contacters, comparator);

                int p = 0;
                for (int i = 0; i < contacters.size(); i++) {
                    Contacter c = contacters.get(i);
                    if (!letterIndex.containsKey(c.getFirstLeater())) {
                        letterIndex.put(c.getFirstLeater(), p);
                        p++;
                        mContactSectionEntities.add(new ContactSection(true, c.getFirstLeater()));
                    }
                    p++;
                    mContactSectionEntities.add(new ContactSection(c));

                }
                return contacters;
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<List<Contacter>>(getContext()) {
                    @Override
                    public void onStart() {
                        showProgress(false);
                    }

                    @Override
                    public void onNext(List<Contacter> contacters) {
                        showContent(false);
                        mContactAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    public void onTouchingLetterChanged(String s) {

//        letterOverlay.setText(s);
//        letterOverlay.setVisibility(View.VISIBLE);
        letterOverlay.removeCallbacks(overlayThread);
        if (letterIndex.get(s) != null) {
            int position = letterIndex.get(s);


            LogUtil.e("position = " + position);

            mRvContact.smoothScrollToPosition(position);
//            city_container.setSelection(position);
            Pattern pattern = Pattern.compile("^[A-Za-z]+$");
            if (pattern.matcher(s).matches()) {
                letterOverlay.setTextSize(40);
            } else {
                letterOverlay.setTextSize(20);
            }
            letterOverlay.setText(s);
            letterOverlay.setVisibility(View.VISIBLE);
        }
    }


    private void initOverlay() {
        overlayThread = new ContactFragment.OverlayThread();
//        isOverlayReady = true;
        LayoutInflater inflater = LayoutInflater.from(getContext());
        letterOverlay = (TextView) inflater.inflate(com.iasii.app.citylist.R.layout.v_letter_overlay, null);
//        letterOverlay.setText("F");
        letterOverlay.setVisibility(View.INVISIBLE);

        int width = DensityUtil.dp2px(getContext(), 65);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                width, width,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getActivity().getSystemService(Context.WINDOW_SERVICE);

        windowManager.addView(letterOverlay, lp);
    }


    private class OverlayThread implements Runnable {
        @Override
        public void run() {
            letterOverlay.setVisibility(View.GONE);
        }
    }


}
